# _*_ coding:utf-8 _*_
# @File  : account.py
# @Time  : 2021-11-30  13:56
# @Author: zizle

from fastapi import APIRouter, Body, Depends, Path
from pydantic import BaseModel, constr, confloat

from db import FAConnection
from utils.encryptor import generate_random_string
from interfaces.depends import logged_require
from status import r_status

account_api = APIRouter()


class AccountItem(BaseModel):
    account_name: constr(min_length=2, max_length=10)
    initial_funds: confloat(ge=10000, le=100000000)


# 用户创建一个投资号
@account_api.post('/', summary='用户创建一个投资账户')
async def create_investment_account(person: dict = Depends(logged_require), account_item: AccountItem = Body(...)):
    # 955 + 5位随机 + %7d ID ,0以随机字母替代  (总15位)
    id_str = str(person['uid'])
    alpha_length = 7 - len(id_str)
    digit_str = generate_random_string(length=5, isdigit=True)
    alpha_str = generate_random_string(length=alpha_length, isalpha=True, alluper=True)
    account = '955' + digit_str + id_str + alpha_str

    db_conn = FAConnection(conn_name='添加投资号')
    count_obj = db_conn.query('SELECT COUNT(id) AS t FROM user_invest_account WHERE user_id=%s;', param=[person['uid']],
                              keep_conn=True, fetchone=True)[0]
    if count_obj['t'] >= 6:  # 一个账户最多创建6个投资号
        db_conn.close()
        return {'code': r_status.VALIDATE_ERROR, 'message': '一个用户最多只能创建6个投资号!'}
    insert_sql = 'INSERT INTO user_invest_account (user_id,account_name,account,i_fund,r_fund) ' \
                 'VALUES (%s,%s,%s,%s,%s);'
    fund = account_item.initial_funds
    _, success = db_conn.insert(insert_sql, param=[person['uid'], account_item.account_name, account,
                                                   fund, fund])
    if success:
        return {'code': r_status.CREATED_SUCCESS, 'message': '创建投资号成功!'}
    else:
        return {'code': r_status.SERVER_ERROR, 'message': '创建投资号失败，服务器错误!'}


# 查询用户的投资号
@account_api.get('/', summary='请求用户下投资号')
async def get_investment_account(person: dict = Depends(logged_require)):
    sql = 'SELECT * FROM user_invest_account WHERE user_id=%s;'
    db_conn = FAConnection(conn_name='查询投资号')
    records = db_conn.query(sql, param=[person['uid']])
    for item in records:
        item['create_date'] = item['create_time'].strftime('%Y-%m-%d')
    return {'code': r_status.SUCCESS, 'message': '查询投资号成功!', 'data': records}


# 登录投资号
@account_api.post('/{account_id}/', summary='登录投资号')
async def account_login(account_id: int = Path(...)):
    db = FAConnection(conn_name='投资号登录')
    sql = 'SELECT id,account_name,account,i_fund,r_fund,b_fund FROM user_invest_account WHERE id=%s LIMIT 1;'
    obj = db.query(sql, param=[account_id], fetchone=True)[0]

    if not obj:
        return {'code': r_status.NOT_CONTENT, 'message': '账户不存在!', 'data': []}
    else:
        obj['available'] = round(obj['r_fund'] - obj['b_fund'], 2)
        obj['using_rate'] = str(round(obj['b_fund'] / obj['r_fund'], 4) * 100) + '%'
        return {'code': r_status.SUCCESS, 'message': '登录成功!', 'data': obj}

